﻿#include "Sender.h"

Sender::Sender(asio::io_context& context, const asio::ip::address& addr)
	:endpoint_(addr, multicast_port_)
	, socket_(context, endpoint_.protocol())
	, timer_(context)
{
	do_send();
}

void Sender::do_send()
{
	std::ostringstream os;
	os << "message: " << message_count_++ << std::endl;
	message_ = os.str();
	std::cout << "sender:" << message_;
	socket_.async_send_to(asio::buffer(message_), endpoint_, [this](const system::error_code &ec, std::size_t) {
		if (!ec && this->message_count_ < message_limit_) {
			do_timeout();
		}
		});
}

void Sender::do_timeout()
{
	timer_.expires_after(std::chrono::seconds(1));
	timer_.async_wait([this](const boost::system::error_code &ec) {
		if (!ec) {
			this->do_send();
		}
		});
}